<template>
  <div class="">
    <!-- 门牌空间查询 -->
    <PagePanel :panelTitle="activePanel.panelTitle" @clickClose="clickClose">
      <el-card class="box-card"
        >提示：点击门牌图标，查看建筑信息、关联的门牌信息。</el-card
      >
      <el-card style="margin-top: 10px" class="box-card">
        <div slot="header" class="clearfix">
          <span>建筑信息</span>
        </div>
        <div
          v-for="(item, index) in houseNumInfoName"
          :key="index"
          class="text item"
        >
          <span style="font-size: 14px; font-weight: 700; color: #2d7ad6">{{
            item.value
          }}</span>
          :{{ houseNumInfo[item.name] }}
        </div>
      </el-card>
    </PagePanel>
  </div>
</template>

<script>
import PagePanel from "@/components/PagePanel";
import markerImg from "../../../assets/img/houseNumSpace.png";
import { getDoorplateAll, findDoorplateInfo } from "@/api/home";
//图标集合
let billboards = null;
export default {
  name: "HouseNumSpaceSearch",
  components: { PagePanel },
  data() {
    return {
      handler: null,
      houseNumInfo: {},
      houseNumInfoName: [
        { name: "name", value: "名称" },
        { name: "doorplate", value: "门牌" },
        // { name: "DongJing", value: "东经" },
        // { name: "BeiWei", value: "北纬" },
        { name: "JZWGD", value: "高度"},
        { name:"JGRQ", value: "竣工日期"},
        { name:"ZDDM", value: "宗地代码"},
        {name: 'ZYDMJ', value:'面积'}
      ],
    };
  },
  computed: {
    activePanel() {
      return this.$store.state.activePanel;
    },
  },
  mounted() {
    this.setCamera();
    this.houseNumSpaceSearch();
    this.leftClickDoorPlate();
  },
  methods: {
    setCamera() {
      const position = Cesium.Cartesian3.fromDegrees(
        113.53837896811851,
        29.494393794297192,
        13843.248808273454
      );
      cesiumViewer.camera.flyTo({
        destination: position, // 相机位置
        orientation: {
          heading: 6.283185307179577, // 水平旋转  -正北方向
          pitch: -1.5689633255085216, // 上下旋转  --俯视朝向
          roll: 0, // 视口翻滚角度
        },
      });
    },
    leftClickDoorPlate() {
      this.handler = new Cesium.ScreenSpaceEventHandler(cesiumViewer.canvas); //获取地图对象
      this.handler.setInputAction((e) => {
        const pick = cesiumViewer.scene.pick(e.position);
        // if (pick && pick?.id) {
        //   alert(JSON.stringfy(pick.properties));
        // }
        if (pick && pick?.primitive) {
          if (pick.primitive.properties.name) {
            // alert(pick.primitive.properties.BiaoZhunMin)
            const id = pick.primitive.properties.id;
            // findDoorplateInfo(id).then((response) => {
              // this.houseNumInfo = JSON.parse(response.data);
              this.houseNumInfo = pick.primitive.properties;

              if(!this.houseNumInfo.name && this.houseNumInfo.XMMC && this.houseNumInfo.JZWMC) {
                this.houseNumInfo.name = this.houseNumInfo.XMMC + this.houseNumInfo.JZWMC;
              }
              

              // this.houseNumInfo.DongJing =
              //   Number(this.houseNumInfo.DongJing) / 10000;
              // this.houseNumInfo.BeiWei =
              //   Number(this.houseNumInfo.BeiWei) / 10000;
              //未返回position
              // this.houseNumInfo.DongJing = Number(
              //   this.houseNumInfo.position.split(",")[0]
              // );
              // this.houseNumInfo.BeiWei = Number(
              //   this.houseNumInfo.position.split(",")[1]
              // );

              console.log(this.houseNumInfo);
            // });
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //鼠标经过 显示名字
      this.handler.setInputAction((e) => {
        cesiumViewer.entities.removeById("houseNumLabel");
        const pick = cesiumViewer.scene.pick(e.endPosition);
        if (pick && pick.primitive) {
          cesiumViewer.entities.add({
            id: "houseNumLabel",
            position: pick.primitive.position,
            label: {
              text: pick.primitive.properties.name,
              pixelOffset: new Cesium.Cartesian2(0, -90),
            },
          });
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    async houseNumSpaceSearch() {
      const res = await getDoorplateAll();
      if (res.code === 20000 && res.data !== 0) {
        const info = JSON.parse(res.data);
        this.addBillboards(info);
      }
    },
    /**
     * 以primitive方式加载
     * @param {*} info
     */
    addBillboards(info) {

      const getCenter = (positions) => {
        const arrs = positions.split(',');
        let minx = Number(arrs[0]);let miny = Number(arrs[1]);let maxx = Number(arrs[0]);let maxy = Number(arrs[1]);
        for(let i =0;i< arrs.length;i+=2) {
          const x = Number(arrs[i]);
          const y = Number(arrs[i+1]);
          if(minx > x){ minx = x}
          if(maxx < x){ maxx = x}
          if(miny > y){ miny = y}
          if(maxy < y){ maxy = y}
        }
        return [(minx + maxx) / 2, (miny + maxy) / 2]
      }

      const features = [];
      info.map((item) => {
        // const positions = item.positions;
        let positions = [];
        if(item.positions){
          positions = build.positions.split(',')
        }else {
          let positionsStr = item.ZB
          // MULTIPOLYGON (((113.34793105317567 29.279366717599999, 113.34787099824803 29.279268034092524, 113.34797350477345 29.279220240521738, 113.34803318018714 29.279318032801029, 113.34793105317567 29.279366717599999)))
          positionsStr = positionsStr.replace('MULTIPOLYGON (((', '').replace(')))','')
          positionsStr.split(',').map((item, index) => {
            item.split(' ').map((item2, index2) => {
              if(item2 !== ' ' && item2 !== '') {
                positions.push(item2)
              }
            })
          })
        }
        const center = getCenter(positions.join(','));
        const feature = {
          properties: {
            ...item,
            center
          },
          coordinates: center,
        };
        features.push(feature);
      });

      billboards = cesiumViewer.scene.primitives.add(
        new Cesium.BillboardCollection()
      );

      let feature, coordinates, position;
      for (let i = 0; i < features.length; i++) {
        feature = features[i];
        coordinates = feature.coordinates;
        position = Cesium.Cartesian3.fromDegrees(
          coordinates[0],
          coordinates[1],
          0
        );
        // pointCollection.add({
        //     position : Cesium.Cartesian3.fromDegrees(longitude, latitude),
        //     color : color
        // });
        const b = billboards.add({
          id: feature.properties.id,
          width: 80,
          height: 80,
          position: position,
          image: markerImg,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          // data: { community, gridsMini, housingEstate, lat, lng, structure },
          properties: feature.properties,
          // scaleByDistance
          // translucencyByDistance = new Cesium.NearFarScalar(1.5e2, 1.0, 8.0e6, 0.0);
        });
        b.properties = feature.properties;
      }
      cesiumViewer.zoomTo(billboards);
    },
    //添加广告牌
    addBillboard(position) {
      //position为cartsian3
      viewer.entities.add({
        position: position, // Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
        billboard: {
          image: "gisdata/images/marker.png",
          sizeInMeters: true,
          scale: 0.1,
          show: true,
          width: 100,
          height: 100,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            6.8e10
          ),
        },
      });
    },
    removeClick() {
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      this.handler.destroy();
    },
    clickClose() {
      console.log("@@@@@@@@@@@@", this.activePanel);
    },
  },
  beforeDestroy() {
    cesiumViewer.entities.removeById("houseNumLabel");
    cesiumViewer.scene.primitives.remove(billboards);
    billboards = null;
    this.removeClick();
    //因为面板都是用的v-if，会销毁面板，需要销毁的事件也可以写这里
  },
};
</script>
<style lang="less" scoped></style>
